package com.bsj.travel.mqtt.cluster;

import cn.hutool.core.net.NetUtil;
import com.bsj.travel.mqtt.enums.RedisKeys;
import com.bsj.travel.util.ip.GetEth0IpUtil;
import net.dreamlu.iot.mqtt.core.server.MqttServer;
import net.dreamlu.iot.mqtt.core.server.MqttServerCreator;
import net.dreamlu.mica.core.utils.CharPool;
import net.dreamlu.mica.core.utils.INetUtil;
import net.dreamlu.mica.redis.cache.MicaRedisCache;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.SmartInitializingSingleton;

/**
 * @author yinhao
 * @version 1.0
 * @description mqtt 服务节点管理
 * hash结构： key "mqtt:server:nodes:"  field "192.168.130.120"  value "192.168.130.120:1883"
 * @date 2023/11/9
 */
public class MqttServerManageRedis implements SmartInitializingSingleton, DisposableBean {
    private final MicaRedisCache micaRedisCache;
    /**
     * 节点名 192.168.130.120
     */
    private final String nodeName;
    /**
     * 主机名 192.168.130.120:1883
     */
    private final String hostName;

    public MqttServerManageRedis(MicaRedisCache redisCache, MqttServer mqttServer) {
        this.micaRedisCache = redisCache;
        this.nodeName = GetEth0IpUtil.getHostAddress();
        this.hostName = getHostName(mqttServer.getServerCreator());
    }

    @Override
    public void destroy() {
        micaRedisCache.hDel(RedisKeys.SERVER_NODES.getKey(), nodeName);
    }

    @Override
    public void afterSingletonsInstantiated() {
        Object node = micaRedisCache.hGet(RedisKeys.SERVER_NODES.getKey(), nodeName);
        if (node != null) {
            micaRedisCache.del(RedisKeys.CONNECT_STATUS.getKey(nodeName));
            micaRedisCache.hDel(RedisKeys.SERVER_NODES.getKey(), nodeName);
        }
        micaRedisCache.hSet(RedisKeys.SERVER_NODES.getKey(), nodeName, hostName);
    }

    private static String getHostName(MqttServerCreator mqttServerCreator) {
        return GetEth0IpUtil.getHostAddress() + CharPool.COLON + mqttServerCreator.getPort();
    }
}
